package cn.iocoder.aics.module.member.controller.app.chathistory;

import cn.iocoder.aics.module.member.controller.app.chathistory.vo.ChatRequest;
import cn.iocoder.aics.module.member.service.chathistory.StreamService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import javax.annotation.security.PermitAll;

@RestController
@RequestMapping("/api/stream")
@RequiredArgsConstructor
public class StreamController {
    private final StreamService streamService;
//    @PermitAll
    @PostMapping("/chat")
    public Flux<ServerSentEvent<String>> streamChat(@RequestBody ChatRequest request) {
        return streamService.streamCompletion(request.toCompletionRequest())
                .map(data -> ServerSentEvent.builder(data)
                        .event("message")
                        .build())
                .onErrorResume(e -> Flux.just(
                        ServerSentEvent.builder("")
                                .event("error")
                                .data(e.getMessage())
                                .build()
                ));
    }
}